<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <div style="text-align: center">
          聊天列表
        </div>
        <div v-for="item in chatList" :class="item.anotherId===messageModel.receiveUserId ? 'act_mes' :'message_list'">
          <div style="display: flex;justify-content: start" @click="selectUser(item)">
            <el-avatar :src="$imgBaseUrl+item.anotherAvatar"></el-avatar>
            <div>
              <p style="font-weight: 800;margin: 0">{{ item.anotherName }}</p>
              <div v-if="item.messages.length!==0">
                <p style="font-size: 10px;margin: 0">{{ item.messages[item.messages.length - 1].content }}</p>
              </div>
            </div>
            <el-badge :value="item.unread" class="item" v-show="item.unread!==0"/>
          </div>
        </div>
      </el-aside>
      <el-container>
        <el-header style="border-style: solid">
          在线
        </el-header>
        <el-main>
          <div v-for="item in chatList" style="margin-top: 10px">
            <div v-if="item.anotherId===messageModel.receiveUserId">
              <div v-for="item2 in item.messages" style="margin-top: 10px">
                <div v-if="item2.sendUserId !== store.loginUser.userId"
                     style="height: 40px;display: flex;justify-content: start">
                  <el-avatar :size="40" :src="$imgBaseUrl+messageModel.anotherAvatar"/>
                  <div class="message_content">
                    {{ item2.content }}
                  </div>
                </div>
                <div v-else style="height: 40px;display: flex;justify-content: end">
                  <div class="message_content">
                    {{ item2.content }}
                  </div>
                  <el-avatar :size="40" :src="$imgBaseUrl+store.loginUser.avatar"/>
                </div>
              </div>
            </div>
          </div>
        </el-main>
        <el-footer style="border-style: solid;height: 200px">
          <el-input v-model="messageModel.content" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="请输入内容">
            <template #suffix>
              <el-button @click="submitMessage">发送</el-button>
            </template>
          </el-input>
        </el-footer>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch} from 'vue'
import {getMessageList, getOpenChatLists, createConversation} from "@/api/home/communication/chat";
import {useMenusStore} from "@/store/permission";
import {useCommonStore} from "@/store";

const store = useMenusStore()
const commonStore = useCommonStore()
let chatList = ref([])

let messageModel = reactive({
  receiveUserId: '',
  content: '',
  type: '0',
  sendType: "backendUser",
  sendUserId: store.loginUser.userId,
  anotherAvatar: ''
})

function getChatList() {
  getOpenChatLists().then((res) => {
    chatList.value = res.data
  })
}

// function webSocketOpen() {
//   if (!ws.value) {
//     ws.value = new WebSocket(process.env.VUE_APP_BASE_API + "/ws/" + getToken('token'))
//     ws.value.onopen = (event) => {
//       console.log('WebSocket is open now.');
//     };
//     ws.value.onmessage = function (event) {
//       let msg = JSON.parse(event.data)
//       chatList.value.forEach(item => {
//         //如果是对方发过来的消息，就存在对应的列表里面
//         if (item.anotherId === msg.sendUserId) {
//           item.messages.push(msg)
//         }
//       })
//       console.log('Received data from server:',msg);
//     }
//   }
// }

function selectUser(item) {
  messageModel.receiveUserId = item.anotherId
  messageModel.anotherAvatar = item.anotherAvatar
  item.messages = []
  getMessageList(item.anotherId).then(res => {
    item.messages.push(...res.data)
  })
}

function submitMessage() {
  if (messageModel.content.length===0 || messageModel.content.trim()===''){
    return
  }
  let message = JSON.stringify(messageModel)
  // ws.value.send(message)
  console.log("我要发送消息了")
  commonStore.sendMessage(message)
  chatList.value.forEach(item => {
    if (item.anotherId === messageModel.receiveUserId) {
      item.messages.push(messageModel)
    }
  })
  //保存数据
  createConversation(messageModel).finally(() => {
    messageModel.content = ''
  })
}

//监听收到的message
// commonStore.$subscribe((mutation,state)=>{
//   console.log("发生了变化",state)
// })

watch(() => commonStore.message, () => {
  console.log("收到消息")
  if (commonStore.message.sendType === "backendUser") {
    chatList.value.forEach(item => {
      //如果是对方发过来的消息，就存在对应的列表里面
      if (item.anotherId === commonStore.message.sendUserId) {
        item.messages.push(commonStore.message)
      }
    })
  }
})
onMounted(() => {
  getChatList()
})

</script>

<style scoped>
.binglie {
  display: flex;
  justify-content: space-between;
}

.message_list {
  height: 50px;
  border-style: solid none none none;
}

.act_mes {
  background-color: antiquewhite;
}

.message_list:hover {
  background-color: antiquewhite;
}

.chatWindow {
  border: solid;
  width: 930px;
  height: 400px;
  border-radius: 4px;
}

.chatWindow_header {
  background-color: gray;
}

.el-main {
  border-style: solid;
  height: 300px;
}

.infinite-list {
  height: 300px;
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}

.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}

.el-header {
  background-color: antiquewhite;
}

.message_content {
  background-color: #8c939d;
  color: white;
  padding: 6px
}
</style>
